package cn.uniquesoft.api;

import cn.uniquesoft.service.IUserService;
import cn.uniquesoft.util.ContextUtil;
import cn.uniquesoft.util.FileUpUtil;
import cn.uniquesoft.vo.AnswerVO;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author wty
 * @connection 1440631589
 * @DESCRIPTION 个人信息部分
 * @create 2018/12/27
 */
@RestController
@RequestMapping(value = "/api/profile")
public class ApiProfileController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/changeHead")
    public AnswerVO changeHead(MultipartFile image,int userid) {
        AnswerVO answerVO = new AnswerVO();
        String tomurl = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/");
        String filepath = "files"+ File.separator + "head" + File.separator;
        String fileFolder = tomurl+filepath;
        File upload = new File(fileFolder);
        if(!upload.exists()) {
            upload.mkdirs();
        }
        // 获得上传文件原始名
        String oldname = image.getOriginalFilename();
        // 算出后缀名
        String ext = oldname.substring(oldname.lastIndexOf("."));
        // 文件名为：名称 + userid + image + UUID + 后缀
        String fileName = "head_" + userid + ext;
        FileUpUtil.fileUpload(tomurl + filepath + fileName, image);
        try {
            Thumbnails.of(tomurl + filepath + fileName)
                    .scale(1f)
                    .outputQuality(0.5f)
                    .toFile(tomurl + filepath + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.userService.updateHeadUrl(fileName,userid);
        answerVO.setMsg("修改成功");
        answerVO.setSuccess(true);
        answerVO.setData(fileName);
        return answerVO;
    }
}
